<template>
  <el-container class="chat-main">
    <el-aside width="250px" class="chat-aside">
      <ChatList ref="childList" :chatList="chatList" @refreshChatDetail="getChatDetail" v-loading="loading"></ChatList>
    </el-aside>
    <el-main class="content">
      <div class="chat-empty" v-show="chatList.length == 0 || currChat == null">
        <el-empty description="当前内容为空，快来和好友分享你的文件吧"></el-empty>
      </div>
      <ChatContent :chatDetailList="chatDetailList" @busChatContent="sendMessage" :chatInfo="currChat"
        @busClearChatHistory="clearHistory" v-show="chatList.length > 0 && currChat != null" ref="childContent"
        v-loading="chatLoading">
      </ChatContent>
    </el-main>
  </el-container>
</template>

<script>
import ChatList from './chat-list'
import ChatContent from './chat-content'
export default {
  name: "message",
  components: {
    ChatList,
    ChatContent
  },
  data() {
    return {
      currChat: null,
      chatDetailList: [],
      loading: false,
      chatLoading: false,
    }
  },
  mounted() {
    this.getChatList()
    this.$bus.$on('busChatContentFile', (data) => { this.sendMessage(data) })
  },
  methods: {
    webSocketInit() {
      // 没有聊天列表就不初始化
      if (this.chatList.length <= 0) {
        return
      }
      const that = this;
      if (typeof WebSocket == "undefined") {
        this.$message.warning("浏览器暂不支持聊天");
      } else {
        // 实例化socket
        let userId = this.userInfo.id
        const socketUrl = "ws://127.0.0.1:3333/api/chat/" + this.currChat.id + "/" + userId;
        // const socketUrl = "ws://www.lijunxi.site:8091/ws";
        this.socket = new WebSocket(socketUrl);
        // 监听socket打开
        this.socket.onopen = this.handleOnOpen
        // 监听socket消息接收
        this.socket.onmessage = this.handleOnMessage
        // 监听socket错误
        this.socket.onerror = function () { };
        // 监听socket关闭
        this.socket.onclose = this.handleOnClose
      }
    },
    // 发送websocket 消息
    sendMessage(data) {
      if (!window.WebSocket) {
        this.$message.warning("浏览器不支持WebSocket")
        return;
      }
      else if (this.chatList <= 0) {
        this.$message.warning("无聊天对象，无法发送")
        return;
      }

      // 发送消息
      let socket = this.socket
      let dataObj = this.getSendMsgItem(this.userInfo, data);
      if (socket.readyState == WebSocket.OPEN) {
        socket.send(JSON.stringify(dataObj));
      } else {
        this.$message.warning("WebSocket 连接没有建立成功！");
      }
    },
    // 打开链接
    handleOnOpen() {
      // console.log("浏览器WebSocket已打开");
    },
    // 接收消息
    handleOnMessage(messageEvent) {
      // 聊天列表显示数据
      this.$refs.childList.getContent(JSON.parse(messageEvent.data))
      // 聊天内容显示数据
      this.$refs.childContent.getContent(JSON.parse(messageEvent.data))
      // 保存本地
      this.saveLocal(JSON.parse(messageEvent.data), 2);
    },
    // 关闭连接
    handleOnClose() {
      let socket = this.socket
      if (socket != null) {
         socket.close()
      }
    },
    // 封装参数
    getSendMsgItem(userInfo, data) {
      let userId = userInfo.id;
      let res = {
        fromUsername: userInfo.username,
        fromAvatar: userInfo.avatar,
        fromNickname: userInfo.nickname,
        content: data.content,
        fileList: data.fileList,
        fromUserId: userId,
        chatId: this.currChat.id,
        type: this.currChat.type,
      }
      if (this.currChat.type == 1) {
        let userList = this.currChat.userList;
        userList.forEach(item => {
          if (item.id != userId) {
            res['toAvatar'] = item.avatar
            res['toUsername'] = item.username
            res['toNickname'] = item.nickname
            res['toUserId'] = item.id
          }
        });
      }
      return res;
    },
    // 请求聊天列表
    async getChatList() {
      this.loading = true
      let res = await this.$store.dispatch('getChatList')
      this.loading = false
      if (!res.success) this.$global.resError(res)
    },
    // 请求聊天记录
    async getChatDetail(chatInfo) {
      // 相同的聊天就不用再次创建连接
      if (this.currChat != null && chatInfo.id == this.currChat.id) {
        return
      }
      this.chatDetailList = []
      this.currChat = chatInfo
      this.chatLoading = true
      // 请求数据
      let res = await this.$store.dispatch("getChatDetailList", {
        id: chatInfo.id
      })
      if (!res.success) this.$global.resError(res)
      else {
        this.webSocketInit();
        this.saveLocal(res.data, 1)
        this.chatLoading = false
      }
    },
    // 保存记录到本地
    saveLocal(data, flag) {
      let key = "chat_history:" + this.userInfo.id + ":" + this.currChat.id + ":";
      let strList = localStorage.getItem(key), localList = [];
      if (strList == null || strList == undefined) {
        localList = [];
      }
      else localList = JSON.parse(strList);
      if (flag == 1) {
        localList = localList.concat(data)
        this.chatDetailList = this.chatDetailList.concat(localList);
      }
      else localList.push(data)
      localStorage.setItem(key, JSON.stringify(localList));
    },
    // 清除聊天记录
    clearHistory() {
      let key = "chat_history:" + this.userInfo.id + ":" + this.currChat.id + ":";
      localStorage.removeItem(key);
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo || {}
    },
    chatList() {
      return this.$store.state.im.chatList || []
    },
    // chatDetailList() {
    //   return this.$store.state.im.chatDetailList || []
    // }
  },
  beforeDestroy() {
    if (this.chatList > 0) {
      this.socket.close();
    }
    this.$bus.$off('busChatContentFile')
    this.handleOnClose()
  }
}
</script>

<style scoped>
.chat-aside {
  height: 100%;
  border-right: 1px solid #f1f2f4;
}

.chat-main {
  height: 100%;
}

.content {
  background-color: #ffff;
}

.chat-empty {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>